package com.itheima.controller;

import com.itheima.commit.R;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String pathname;

    @PostMapping("/upload")
    public R<String> common(MultipartFile file){

        String filename = file.getOriginalFilename();

        String substring = filename.substring(filename.lastIndexOf("."));

        String s = UUID.randomUUID().toString()+substring;

        String fname = pathname+s;

        File file1 = new File(fname);

        if (!file1.exists()) {
            file1.mkdirs();
        }

        try {
            file.transferTo(new File(fname));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(s);
    }
    @GetMapping("/download")
    public void download(HttpServletResponse response ,String name){
        try {
            FileInputStream fis = new FileInputStream(new File(pathname+name));
            ServletOutputStream stream = response.getOutputStream();

            response.setContentType("image/jpeg");

            IOUtils.copy(fis,stream);
            /*byte[] bytes = new byte[1024];
            int len;

            while ((len = fis.read(bytes)) != -1) {
                stream.write(bytes,0,len);
            }*/
            fis.close();
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
